package com.kaichaohulian.baocms.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.kaichaohulian.baocms.R;
import com.kaichaohulian.baocms.app.MyApplication;
import com.kaichaohulian.baocms.base.BaseActivity;
import com.kaichaohulian.baocms.entity.BankCardEntity;
import com.kaichaohulian.baocms.http.HttpUtil;
import com.kaichaohulian.baocms.http.Url;
import com.kaichaohulian.baocms.utils.DBLog;
import com.kaichaohulian.baocms.view.ShowDialog;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import static com.kaichaohulian.baocms.R.id.add_bankcard_realname_edit;

/**
 * 添加银行卡
 */
public class AddBankCardActivity extends BaseActivity {

    private Spinner editTextOpenBank;
    private EditText editTextName, editTextPhone, editTextCardNumber, add_bankcard_real_idcard_edit;
    private Button btnConfirm;

    private String[] data = {"工商银行", "农业银行", "建设银行", "中信银行", "中国银行", "招商银行"};
    private int index = 0;

    @Override
    public void setContent() {
        setContentView(R.layout.add_bank_card_layout);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        setCenterTitle("添加银行卡");
        editTextName = getId(add_bankcard_realname_edit);
        editTextPhone = getId(R.id.add_bankcard_real_phone_edit);
        editTextCardNumber = getId(R.id.add_bankcard_real_cardnumbers);
        editTextOpenBank = getId(R.id.add_bankcard_real_banks_edit);
        btnConfirm = getId(R.id.add_bankcard_btn);
        add_bankcard_real_idcard_edit = getId(R.id.add_bankcard_real_idcard_edit);

        editTextCardNumber.setInputType(EditorInfo.TYPE_CLASS_NUMBER);

//        editTextCardNumber.addTextChangedListener(new MyTextWatcher());
//        editTextPhone.addTextChangedListener(new MyTextWatcher());
//        editTextName.addTextChangedListener(new MyTextWatcher());
//        add_bankcard_real_idcard_edit.addTextChangedListener(new MyTextWatcher());

        editTextOpenBank.setAdapter(new Adapter());
    }

    String name;
    String phoneNumber;
    String cardnumber;
    String openBank;

    @Override
    public void initEvent() {
        editTextOpenBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                index = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (TextUtils.isEmpty(add_bankcard_real_idcard_edit.getText().toString())) {
                    showToastMsg("请输入身份证号");
                    return;
                } else if (TextUtils.isEmpty(editTextName.getText().toString())) {
                    showToastMsg("请输入姓名");
                    return;
                } else if (TextUtils.isEmpty(editTextPhone.getText().toString())) {
                    showToastMsg("请输入预留手机号");
                    return;
                } else if (TextUtils.isEmpty(editTextCardNumber.getText().toString())) {
                    showToastMsg("请输入银行卡号");
                    return;
                }
                if (editTextCardNumber.getText().toString().length() < 4) {
                    showToastMsg("银行卡号最少四位");
                    return;
                }
                btnConfirm.setEnabled(false);

                getBindBankCard();


            }
        });
    }


    public void getBindBankCard() {
        name = editTextName.getText().toString();
        phoneNumber = editTextPhone.getText().toString();
        cardnumber = editTextCardNumber.getText().toString();
        openBank = data[index];
        RequestParams params = new RequestParams();
        params.put("id", MyApplication.getInstance().UserInfo.getUserId());
        params.put("username", name);
        params.put("idcard", add_bankcard_real_idcard_edit.getText().toString());
        params.put("bankName", openBank);
        params.put("cardNo", cardnumber);

        HttpUtil.post(Url.BindCard, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    ArrayList<BankCardEntity> list = new ArrayList<>();
                    DBLog.e("获取银行卡:", response.toString());
                    if (response.getInt("code") == 0) {
                        JSONArray array = response.getJSONArray("dataObject");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            BankCardEntity entity = new BankCardEntity();
                            entity.setId(object.getInt("id"));
                            entity.setCreatedTime(object.getString("createdTime"));
                            entity.setCreator(object.getInt("creator"));
                            entity.setIsLocked(object.getBoolean("isLocked"));
                            entity.setLastModifiedTime(object.getString("lastModifiedTime"));
                            entity.setLastModifier(object.getInt("lastModifier"));
                            entity.setTimeStamp(object.getString("timeStamp"));
                            entity.setCardNo(object.getString("cardNo"));
                            entity.setCardType(object.getString("cardType"));
                            entity.setIdcard(object.getString("idcard"));
                            entity.setUsername(object.getString("username"));
                            entity.setOneOuota(object.getString("oneOuota"));
                            entity.setDayusername(object.getString("dayusername"));
                            entity.setBankName(object.getString("bankName"));
//                            entity.setNumberAll(object.getString("cardNo"));
                            list.add(entity);
                        }

                    }
                    Intent intent = new Intent();
                    intent.putExtra("username", name);
                    intent.putExtra("phoneNumber", phoneNumber);
                    intent.putExtra("cardNo", cardnumber);
                    intent.putExtra("openbank", openBank);
                    intent.putExtra("cardType", "0");
                    intent.putExtra("idcard", add_bankcard_real_idcard_edit.getText().toString());
//                    Toast.makeText(AddBankCardActivity.this, "绑卡成功了", Toast.LENGTH_SHORT).show();
                    setResult(100, intent);
                    finish();
                } catch (Exception e) {
                    showToastMsg("获取银行卡，解析json异常");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToastMsg("请求服务器失败");
                DBLog.e("tag", statusCode + ":" + responseString);
                ShowDialog.dissmiss();
            }
        });
    }


    public void bindBankCark() {

        final RequestParams params = new RequestParams();
        params.put("page", 1);

        HttpUtil.post(Url.platForm, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {


            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                DBLog.e("tag", statusCode + ":" + responseString);
                ShowDialog.dissmiss();

            }

            @Override
            public void onCancel() {
//                Toast.makeText(getActivity(), "请求取消", Toast.LENGTH_SHORT).show();
                ShowDialog.dissmiss();
            }
        });

    }
//    class MyTextWatcher implements TextWatcher {
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            boolean s1 = editTextCardNumber.getText().length() >= 16;
//            boolean s2 = editTextName.getText().length() > 0;
//            boolean s3 = add_bankcard_real_idcard_edit.getText().length() == 18;
//            boolean s4 = editTextPhone.getText().length() == 11;
//            if (s1 && s2 && s3 && s4) {
//                btnConfirm.setEnabled(true);
//                btnConfirm.setBackground(getResources().getDrawable(R.mipmap.deepgreen_bar));
//            } else {
//                btnConfirm.setEnabled(false);
//                btnConfirm.setBackgroundColor(getResources().getColor(R.color.action_bar_tittle_color));
//            }
//        }
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//        }
//
//        @Override
//        public void afterTextChanged(Editable s) {
//
//
//        }
//    }

    public class Adapter extends BaseAdapter {
        @Override
        public int getCount() {
            return data.length;
        }

        @Override
        public String getItem(int position) {
            return data[position];
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_text, null);
            TextView title = (TextView) convertView.findViewById(R.id.tv_title);
            title.setText(data[position]);
            return convertView;
        }
    }
}
